package oj;

/**
 * @author 郝文雪
 * @date 2022/8/18 11:45
 * @Description Test
 */
public class LC43 {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) return "0";
        String res="0";
        for(int i=num2.length()-1;i>=0;i--){
            int carry=0;
            StringBuilder sb=new StringBuilder();
            for(int j=0;j<num2.length()-1-i;j++){
                sb.append("0");
            }
            int n2=num2.charAt(i)-'0';
            for(int j=num1.length()-1;j>=0 || carry!=0;j--){
                int n1=j<0?0:num1.charAt(j)-'0';
                int product=(n1*n2+carry)%10;
                sb.append(product);
                carry=(n1*n2+carry)/10;
            }
            res=addStrings(res,sb.reverse().toString());
        }
        return res;
    }
    private String addStrings(String s1,String s2){
        int carry=0;
        StringBuilder sb=new StringBuilder();
        for(int i=s1.length()-1,j=s2.length()-1;i>=0 || j>=0 || carry!=0;i--,j--){
            int n1=i<0?0:s1.charAt(i)-'0';
            int n2=j<0?0:s2.charAt(j)-'0';
            int product=(n1+n2+carry)%10;
            sb.append(product);
            carry=(n1+n2+carry)/10;
        }
        return sb.reverse().toString();
    }
}
